// pages/index/sendblessings.js
const config = require('../../config')
const util = require('../../utils/util')
var app = getApp()
const innerAudioContext = wx.createInnerAudioContext()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    types:1,
    recordtips:'长按进行录音',
    recordingvideo:'录制视频',
    recordings: false, //是否正在录音
    tempFilePath: null, //录音资源地址
    recordtime: 0,  //录音时长
    name: '神秘用户',
    avatarurl: 'http://duodianzhufu-1253586992.cosgz.myqcloud.com/Resources/user/avatar.png',
    vides_p:false,  //视频控制是否显示
    ios:false,  //是否IOS
    max_time:600,  //最大录制时长
    camera_state:false,  //录像状态
    camera_switch: false, //相机与播放切换
    back:'back'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    if (e.types ) {
      this.setData({ types: e.types })
    }
    if (app.globalData.nickName){
      this.setData({
        name: app.globalData.nickName,
        avatarurl: app.globalData.avatarUrl
      })
    }
    this.get_blessing()  //获取发送祝福页面信息
    this.auth(e.types)
    
  },
  onReady: function(){
    this.recorderManager = wx.getRecorderManager()
    this.innerAudioContext = wx.createInnerAudioContext()
    this.ctx = wx.createCameraContext()
    //获取手机型号
    wx.getSystemInfo({
      success: function (res) {
        var ios = res.platform
        if (ios == 'ios') {
          that.setData({ios:true})
        }
      }
    })
  },
  //授权判断
  auth: function (types) {
    //调录音授权
    var that = this
      wx.getSetting({
        success(res) {
        if (types == 1&&!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              //wx.startRecord()
              that.endvoice()
            }
          })
        }
        if (types == 2 &&!res.authSetting['scope.camera']) {
          wx.authorize({
            scope: 'scope.camera',
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              //wx.startRecord()
              
            },
            fail:function (res) {
                wx.showModal({
                  title: '提示',
                  content: '小程序需要像机功能权限,点击确认前往设置或退出程序?',
                  
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: (res) => {
                          /*
                          * res.authSetting = {
                          *   "scope.userInfo": true,
                          *   "scope.userLocation": true
                          * }
                          */
                        }
                      })
                    }else{
                      wx.reLaunch({
                        url: '/pages/index/index',
                      })
                    }
                  }
                })
            }
          })
        }
      }
    })
  },

  /**
   * 获取发送祝福页面信息
   */
  get_blessing: function () {
    var that = this
    if (app.globalData.uid) {
      var headerkey = util.createheaderkey()
      wx.request({
        url: config.host + '/api/Sendwish/Sendwish',
        method: 'GET',
        header: {
          'content-type': 'application/json',
          'key': headerkey.key,
          'time': headerkey.timestamp
        },
        data: {
            uid: app.globalData.uid
        },
        success: function (res) {
          if (res.data.code == 200) {
            var data = res.data.data
            that.setData({
              randomWish: data.randomWish[0],
              showGiftList: data.showGiftList,
              showNeedGift: data.showNeedGift,
              name: data.username[0],
              recordMinTime: data.recordMinTime,
              max_time: data.recordMaxTime
            })
          } else {
              wx.showModal({
                  title: '失败',
                  content: res.data.msg,
                  showCancel: false,
                  success: function () {
                      wx.reLaunch({
                          url: '/pages/index/index',
                      })
                  }
              })
          }
        },
        fail: function (res) {
          console.log(res)
        }
      })
    } else {
      setTimeout(function () {
        that.get_blessing()
      }, 1000)
    }
  },

  /**
   * 录音
   */
  //开始录音
  startvoice: function () {
    //录音开始
    var that = this
    that.recorderManager.start({ format: 'aac' })
    //录音授权处理
    that.recorderManager.onError((res) => {
      console.log(res)
      var errMsg = res.errMsg
      if ((errMsg == "operateRecorder:fail:auth denied") || (errMsg == "operateRecorder:fail auth deny")) {
        wx.showModal({
          title: '提示',
          content: '小程序需要录音功能权限,点击确认前往设置或退出程序?',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  /*
                  * res.authSetting = {
                  *   "scope.userInfo": true,
                  *   "scope.userLocation": true
                  * }
                  */
                }
              })
            }
          }
        })
      }
    })
    //记录事件
    that.recorderManager.onStart(() => {
      //console.log('开始录音')
      var starttime = Date.parse(new Date()) / 1000
      that.setData({
        recordtips: '正在录音',
        starttime: starttime,
        recordtime: 0,
        recordings: true
      })
      //0.1秒后修改底部提示文字信息
      setTimeout(function () {
        that.changerecordtips()
      }, 100)
    })
  },

  //结束录音
  endvoice:function(){
    var that = this
    var recordMinTime = that.data.recordMinTime  //最小时长
    //console.log('结束录音了')
    that.recorderManager.stop()
    that.recorderManager.onStop((res) => {
      that.innerAudioContext.src = res.tempFilePath
      var duration = Math.ceil(res.duration / 1000)
      if (duration < recordMinTime) {
        wx.showToast({
          title: '时间太短了哦',
          icon: 'success',
          duration: 2000
        })
        that.setData({
          recordings: false,
          tempFilePath: null
        })
      }else{
        that.setData({
          tempFilePath: res.tempFilePath,
          duration: duration,  //录音时长
          recordings: false
        })
      }
    })
  },
  //修改底部提示信息
  changerecordtips(sort=1){
    var that = this,
        recordings = that.data.recordings
    if (!recordings){
        that.setData({
            recordtips:'重新录制'
        })
    }else{
      sort < 3 ? sort++ : sort = 1
      var recordtime = that.data.recordtime,
          recordtips
      switch (sort) {
        case 1:
            recordtips = '正在录音.'
            break
        case 2:
            recordtips = '正在录音..'
            break
        case 3:
            recordtips = '正在录音...'
            break
      }
      recordtime++
      that.setData({
          recordtime: recordtime,
          recordtips: recordtips,
          hearing_time: recordtime  //试听时长
      })
      if (recordings){
        setTimeout(function () {
            that.changerecordtips(sort)
        }, 1000)
      }
    }
  },
  //试听录音
  audition:function(){
    var that = this,
      tempFilePath = that.data.tempFilePath,
      suspend = that.data.suspend  //播放状态
    if (tempFilePath) {
      if (suspend) {
        //暂停
        that.innerAudioContext.pause()
      }else{
        //播放
        that.innerAudioContext.src = tempFilePath
        that.innerAudioContext.play()
      }
      //开始事件
      that.innerAudioContext.onPlay(() => {
        console.log('开始播放')
        that.setData({ suspend: true })
        that.auditioning_animation()
      })
      //暂停事件
      that.innerAudioContext.onPause(() => {
        console.log('暂停播放')
        that.setData({ suspend: false })
      })
      //自然结束事件
      that.innerAudioContext.onEnded(() => {
        console.log('播放结束')
        that.setData({ suspend: false })
      })
    }
  },
  //试听动画
  auditioning_animation: function () {
    var that = this
    var countdown = that.data.hearing_time
    if (that.data.suspend) {
      //判断倒计时是否结束
      if (countdown <= 0) {
        console.log('播放完')
      } else {
        setTimeout(function () {
          countdown--;
          var showtime = countdown
          that.setData({
            showtime: showtime,
            hearing_time: countdown
          })
          that.auditioning_animation()
        }, 1000)
      }
    }else{
      that.setData({
        hearing_time: that.data.recordtime
      })
    }
  },

  /**
   * 视频
   */
  //相机与播放切换
  camera_switch: function () {
    var that = this
    var camera_switch = that.data.camera_switch
    if (camera_switch) {
      that.setData({
        camera_switch:false
      })
    }else{
      that.setData({
        camera_switch: true
      })
      that.auth(2)
    }
    
  },
  //开始录视频
  video_start: function () {
    var that = this
    var max_time = that.data.max_time
     that.ctx.startRecord({
       success: (res) => {
         console.log(res)
         that.setData({
           camera_state: true,
           max_time1: max_time
         })
         that.count_down()
       },
       complete: function (res) {
         console.log(res)
       },
     })
  },
  //停止录视频
  video_stop: function () {
    var that = this
    var recordMinTime = that.data.recordMinTime  //最小时间
    // var duration = that.data.duration  //录制时长
    var duration = (parseFloat(that.data.max_time1) - parseFloat(that.data.max_time))
    that.ctx.stopRecord({
      success: (res) => {
        var tempFilePath = res.tempVideoPath  //视频
        var tempThumbPath = res.tempThumbPath  //图片
        if (duration < recordMinTime) {
          wx.showToast({
            title: '时间太短了哦',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            tempFilePath: null,
            camera_state: false,  //录像状态
            max_time: that.data.max_time1
          })
        } else {
          that.setData({
            tempFilePath: tempFilePath, //视频
            tempThumbPath: tempThumbPath,  //图片
            duration: duration, //录像时长
            camera_switch: false, //相机与播放切换
            camera_state: false,  //录像状态
            max_time: that.data.max_time1
          })
          that.storage()
        }
      }
    })
  },
  //倒计时
  count_down: function () {
    var that = this
    var max_time = that.data.max_time
    if (that.data.camera_state) {
      //判断倒计时是否结束
      if (max_time <= 0) {
        //console.log('播放完')
        that.video_stop()
      } else {
        setTimeout(function () {
          max_time--;
          var showtime = max_time
          that.setData({
            showtime: showtime,
            max_time: max_time
          })
          that.count_down()
        }, 1000)
      }
    }else{
      that.setData({
        max_time: that.data.max_time1
      })
    }
  },
  //播放视频
  play_video: function (e) {
    var that = this
    var video_src = that.data.tempFilePath
    console.log(video_src)
    that.setData({
      vides_p: true,
      video_src: video_src,
      recordingvideo: "重新录制"
    })
  },
  //相机正反
  positive: function () {
    var that = this
    var back = that.data.back
    if (back == "back") {
      that.setData({
        back: "front"
      })
    }else{
      that.setData({
        back: "back"
      })
    }
  },


  //祝福标题实时更新
  bindinput: function (e) {
    this.setData({ randomWish: e.detail.value})
  },
  //将此祝福设置为“发红包后”可见
  switch1Change: function (e) {
    if (e.detail.value) {
      this.setData({ switch1: 1 })
    }else{
      this.setData({ switch1: 0 })
    }
    console.log('switch1 发生 change 事件，携带值为', e.detail.value)
  },
  //模糊此祝福的打赏红包列表
  switch2Change: function (e) {
    if (e.detail.value) {
      this.setData({ switch2: 1 })
    } else {
      this.setData({ switch2: 0 })
    }
    console.log('switch1 发生 change 事件，携带值为', e.detail.value)
  },

  /**
   * 发送并分享
   */
  //存储
  storage: function () {
    var that = this
    var temp = that.data.tempFilePath  //内容
    if (temp) {
    var types = that.data.types  //分类
    var randomWish = that.data.randomWish  //标题
    var avatarurl = that.data.avatarurl  //头像
    var switch1 = that.data.switch1  //将此祝福设置为“发红包后”可见
    var switch2 = that.data.switch2  //模糊此祝福的打赏红包列表
    var duration = that.data.duration  //时长
    var status = that.data.status  //是否举报
    var headerkey = util.createheaderkey()
    switch1 ? switch1 = switch1 : switch1=0
    switch2 ? switch2 = switch2 : switch2=0
    if (app.globalData.uid) {
      //提示上传中
      wx.showLoading({
        title: '加载中....',
        mask: true
      })
      //以下为设置文件名
      var Suffix = temp.substring(temp.lastIndexOf("."), temp.length)   //获取图片后缀名
      var formatTime = util.formatTime   //格式化时间戳函数
      var RandomString = util.RandomString //生产随机字符串函数
      var CosName = formatTime(Date.now(), false) + RandomString(10) + Suffix  //生成文件名
      //以下为设置文件路径
      if (types == 1) {
        var CosPath = 'voice/' + app.globalData.uid + '/'
      }else{
        var CosPath = 'video/' + app.globalData.uid + '/'
      }
      //腾讯COS相关配置
      var BucketAppId = config.BucketAppId,
          BucketRegion = config.BucketRegion,
          BucketName = config.BucketName,
          cosUrl = "https://" + BucketRegion + ".file.myqcloud.com/files/v2/" + BucketAppId + "/" + BucketName + '/',
          cosSignatureUrl = config.host + '/api/savewish/sign'  //鉴权服务器地址
      //请求cos服务器签名
      wx.request({
        url: cosSignatureUrl,
        data: {
          folder: CosPath + CosName,
          //bucket: BucketName
        },
        method: 'POST',
        header: {
          'content-type': 'application/json',
          'key': headerkey.key,
          'time': headerkey.timestamp
        },
        success: function (cosRes) {
          // 签名
          var signature = cosRes.data.data
           
          // 头部带上签名，上传文件至COS
          wx.uploadFile({
            url: cosUrl + CosPath + CosName,
            filePath: temp,
            header: {
              'Authorization': signature
            },
            name: 'filecontent',
            formData: {
              op: 'upload',
              insertOnly: 0
            },
            success: function (uploadRes) {
              //修改图片显示路径
              var source = config.filePath + CosPath + CosName

              //将调整好的数据上传到服务器
              wx.request({
                url: config.host + '/api/savewish/savesendwish',
                data: {
                  uid: app.globalData.uid,
                  title: randomWish,
                  //picture: avatarurl,//头像url
                  source: source,//音视频url
                  needgift: switch1,//是否需要红包才能查看音视频
                  giftlist: switch2,//是否屏蔽收红包列表
                  //status: "0",//是否被举报后被管理员屏蔽
                  duration: duration,//音视频时长
                  source_type: types //音视频类型（1语音 2视频）
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json',
                  'key': headerkey.key,
                  'time': headerkey.timestamp
                },
                success: function (res) {
                  if (res.data.code == 200) {
                    wx.hideLoading() //取消加载中图标
                    var wid = res.data.data
                    that.setData({wid})

                    //发送弹窗
                    if (types == 1) {
                      that.setData({
                        share_p: true
                      })
                    } else {
                      that.setData({
                        tempFilePath: source,
                      })
                      that.play_video()
                    }
                  } else {
                    console.log(res)
                  }
                }
              })
            },
            fail: function (e) {
              wx.hideLoading()
              wx.showToast({
                title: '上传失败,请重试',
                icon: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    }else{
      setTimeout(function () {
        that.storage()
      }, 500)
    }
    }
  },
  //取消
  cancel_share: function () {
    var that = this,
      types = that.data.types
    if (types == 1) {
      that.setData({
        share_p: false
      })
    } else {
      that.setData({
        vides_p: true,
        share_p: false
      })
    }
  },
  //发送弹窗
  popup: function () {
    var that = this
    var types = that.data.types
    //发送弹窗
    if (types == 1) {
      that.setData({
        share_p: true
      })
    } else {
      that.setData({
        vides_p: false,
        share_p: true
      })
    }
  },
   
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this
    var wid = that.data.wid
    var title = that.data.randomWish
    var imageUrl = 'http://zhufucnd.xinnar.com/images/share.png'
    console.log(wid)
    return {
      title: title,
      path: '/pages/index/blessing?id=' + wid,
      imageUrl: imageUrl,
      success: function (res) {
        // 转发成功
        wx.redirectTo({
          url: '/pages/index/blessing?id=' + wid,
        })
      },
      fail: function (res) {
        // 转发失败
        wx.redirectTo({
          url: '/pages/index/blessing?id=' + wid,
        })
      }
    }
  },
  //生成朋友圈分享图
  sharing_graph: function () {
    var that = this
    var wid = that.data.wid
    var headerkey = util.createheaderkey()
    //提示生成中
    wx.showLoading({
      title: '生成中....',
      mask: true
    })
    if (app.globalData.uid) {
    //获取分享图
      wx.request({
        url: config.host + '/api/sharepicture/sharepicture?uid=' + app.globalData.uid + '&wid=' + wid,
        data: {

        },
        method: 'GET',
        header: {
          'content-type': 'application/json',
          'key': headerkey.key,
          'time': headerkey.timestamp
        },
        success: function (res) {
          if (res.data.code == 200) {
            wx.hideLoading() //取消加载中图标
            var imageUrl = res.data.data.file
            wx.previewImage({
              current: 'imageUrl', // 当前显示图片的http链接
              urls: [imageUrl] // 需要预览的图片http链接列表
            })
          } else {
            //console.log(res)
          }
        },
        fail: function (error) {
          console.log(error)
        }
      })
    }else{
      setTimeout(function () {
        that.sharing_graph()
      }, 500)
    }
  },

  //保存formid
  saveform: function (e) {
    var formid = e.detail.formId
    app.saveformid(formid)
  },

})